package com.cxso.example.sdk.http.core;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.cxso.example.sdk.domain.Result;
import com.cxso.example.sdk.http.base.ClientInfo;
import com.cxso.example.sdk.http.cache.GenericCache;

import java.util.List;

public class ResultResolver {

    private final String result;
    private final ClientInfo clientInfo;

    public ResultResolver(ClientInfo clientInfo, String result) {
        this.clientInfo = clientInfo;
        this.result = result;
    }

    private Result expire(Result temp) {
        if (temp.getCode() == 410) {
            GenericCache.remove(this.clientInfo.getClientId(), this.clientInfo.getClientSecret());
            return Result.fail("应用令牌已强制下线，可重新尝试操作");
        }
        return temp;
    }

    public Result<?> toResult() {
        JSONObject jsonObject = JSONObject.parseObject(this.result);
        Result temp = jsonObject.toJavaObject(Result.class);
        return expire(temp);
    }

    /**
     * 结果转换为对象
     */
    public <T> Result<T> toEntity(Class<T> t) {
        JSONObject jsonObject = JSONObject.parseObject(this.result);
        Result gatewayResponse = jsonObject.toJavaObject(Result.class, JSONReader.Feature.SupportSmartMatch);
        if (gatewayResponse.getData() != null && gatewayResponse.getData() instanceof JSONObject) {
            if (t != null) {
                if (t.getCanonicalName().equals(JSONObject.class.getCanonicalName())) {
                    gatewayResponse.setData(gatewayResponse.getData());
                } else {
                    JSONObject data = (JSONObject) gatewayResponse.getData();
                    T temp = data.toJavaObject(t);
                    gatewayResponse.setData(temp);
                }
            }
        }
        return expire(gatewayResponse);
    }

    /**
     * 结果转换为数组
     */
    public <T> Result<List<T>> toList(Class<T> t) {
        Result gatewayResponse = JSONObject.parseObject(this.result, Result.class);
        if (gatewayResponse.getData() instanceof JSONArray) {
            if (t.getCanonicalName().equals(JSONArray.class.getCanonicalName())) {
                gatewayResponse.setData(gatewayResponse.getData());
            } else {
                JSONArray data = (JSONArray) gatewayResponse.getData();
                List<T> ts = data.toJavaList(t);
                gatewayResponse.setData(ts);
            }
        }
        return expire(gatewayResponse);
    }
}
